const express = require("express");
const exphbs  = require('express-handlebars');  //引入handlebars模板引擎

//引入body-parser
const bodyParser = require('body-parser');
const jsonParser = bodyParser.json()
const urlencodedParser = bodyParser.urlencoded({ extended: false })
//引入mongoose
const mongoose = require("mongoose");
//引入 method-override
const methodOverride = require('method-override');
const app = express();

//method-override middleware
app.use(methodOverride('_method'));

//连接到mongoose 数据库
mongoose.connect("mongodb://localhost/node-app").then(() =>{
	console.log("连接成功！");
}).catch(err =>{
	console.log(err + "连接失败！")
})
//引入模型
require("./models/Ideas.js");
const Idea = mongoose.model("ideas");

// 设置模板引擎
app.engine('handlebars', exphbs({
	defaultLayout:'main'
}));
app.set('view engine', 'handlebars');

//配置路由
app.get("/" , (req,res) =>{
	const title="这是传过来的title" ;
	res.render("home" , {
		title:title
	});
})
app.get("/about" , (req,res) =>{
	res.render("about");
})
//路由跳转到   *********************************  学习列表界面
app.get("/ideas" , (req,res) =>{
	//find({})查询全部  --  sort()排序
	Idea.find({}).sort({date:"desc"}).lean().then(item =>{
		console.log(item);
		res.render("ideas/index" , {
			learnData:item
		});
		// res.send(ideas);
	})
})
//路由跳转到   *********************************  添加界面
app.get("/ideas/add" , (req,res) =>{
	res.render("ideas/add");
})
//路由跳转到   *********************************  编辑界面
app.get(`/ideas/editor/:id` , (req,res) =>{
	console.log("**************************************!")
	console.log(req.params.id)
	Idea.findOne({
		_id:req.params.id
	}).lean().then( item => {
		res.render("ideas/editor" , {
			idea:item
		});
	})
})
//获取提交数据
app.post("/ideas" , urlencodedParser , (req,res) =>{
	// const req = JSON.stringify(req.body);
	// console.log(obj)
	// res.send("ok");
	const newUser = JSON.stringify({
		title:req.body.title ,
		detail:req.body.detail ,
	})
	new Idea(JSON.parse(newUser)).save().then(item =>{
		res.redirect("/ideas");
	})
})
//实现编辑put 方法
app.put("/ideas/:id" , urlencodedParser , (req,res) => {
	Idea.findOne({_id:req.params.id}).then(item =>{
		item.title = req.body.title ;
		item.detail = req.body.detail ;
		//更新到库
		item.save().then(idea =>{
			// 跳转到列表页
			res.redirect('/ideas');
		})
	})
})
//实现删除DELETE 方法
app.delete("/ideas/:id" , (req , res) =>{
	Idea.remove({_id:req.params.id}).then( () =>{
		// alert("删除成功");
		// 跳转到列表页
		res.redirect('/ideas');
	})
})

const port = 8888;
app.listen(port,() =>{
	console.log("启动端口为 "+ port + "的端口 ");
})